package cn.autumnorange.app.user.consumer.authorization.security.security.basicLogin;

import cn.autumnorange.app.common.rpc.exception.JsonException;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Getter
@Setter
public class JsonBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
  public JsonBasicAuthenticationEntryPoint() {}

  public JsonBasicAuthenticationEntryPoint(String realmName, JsonException jsonException) {
    super.setRealmName(realmName);
    this.jsonException = jsonException;
  }

  private JsonException jsonException;

  @Override
  public void commence(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException authException)
      throws IOException, ServletException {
    //basic认证请求头如下,web浏览器会弹出账号密码登录框
//    response.addHeader("WWW-Authenticate", "Basic realm=\"" + super.getRealmName() + "\"");
    //        response.sendError(HttpStatus.UNAUTHORIZED.value(),
    // HttpStatus.UNAUTHORIZED.getReasonPhrase());
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    jsonException.jsonException(request, response, authException, HttpStatus.UNAUTHORIZED.value());
  }
}
